import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/EventBus.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class MinePage extends StatefulWidget {
  const MinePage(
      {super.key, required this.currentIndex, required this.changeIndex});

  final int currentIndex;
  final Function(int) changeIndex;
  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // @override
  // void initState() {
  //   // TODO: implement initState
  //   super.initState();
  //   PromptAction.showToast('initState${widget.currentIndex}');
  //   print('initState${widget.currentIndex}');
  // }
  Map<String, dynamic> userInfo = {};
  @override
  void didUpdateWidget(covariant MinePage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    if (widget.currentIndex == 1) {
      // 发送请求 -> 获取用户信息
      getUserInfo();
    }
  }

  @override
  void initState() {
    super.initState();
    // 订阅消息 LoginEvent
    registerLoginEvent();
  }

  registerLoginEvent() {
    eventBus.on<LoginEventBus>().listen((event) {
      getUserInfo();
    });
  }

  // 获取用户信息
  Future getUserInfo() async {
    userInfo = await getUserInfoAPI();
    setState(() {});
  }

  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];

  getAvatarImage() {
    if (userInfo['avatar'] != null && userInfo['avatar'].isNotEmpty) {
      if (userInfo['avatar'].startsWith('/data')) {
        return Image.file(
          File(userInfo['avatar']),
          width: 50,
          height: 50,
        );
      } else {
        return Image.network(
          userInfo['avatar'],
          width: 50,
          height: 50,
        );
      }
    } else {
      return Image.asset(
        'assets/images/avatar_1.jpg',
        width: 50,
        height: 50,
      );
    }
  }

  List<Widget> getTitleChild() {
    return [
      ClipRRect(
        borderRadius: BorderRadius.circular(50.0),
        child: getAvatarImage(),
      ),
      const SizedBox(width: 10),
      userInfo['nickName'] != null
          ? Text(userInfo['nickName'],
              style: const TextStyle(fontSize: 16, color: Colors.white))
          : const Text('用户名',
              style: TextStyle(fontSize: 16, color: Colors.white)),
      const Spacer(),
      GestureDetector(
        onTap: () {
          Navigator.pushNamed(context, '/profile', arguments: userInfo);
        },
        child: const Text(
          '去完善信息',
          style: TextStyle(color: Colors.white),
        ),
      )
    ];
  }

  List<Widget> getChildren() {
    return menuList
        .map(
          (item) => SizedBox(
            height: 50,
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                if (item["title"] == '我的房屋') {
                  Navigator.pushNamed(context, "/house");
                }
              },
              child: Row(
                children: [
                  Row(
                    children: [
                      Image.asset(
                        item['icon'],
                        width: 20,
                        height: 20,
                      ),
                      const SizedBox(
                        width: 10,
                      ),
                      Text(
                        item['title'],
                        style: const TextStyle(fontSize: 16),
                      )
                    ],
                  ),
                  const Spacer(),
                  const Icon(
                    Icons.arrow_forward_ios,
                    size: 12,
                    color: Colors.grey,
                  )
                ],
              ),
            ),
          ),
        )
        .toList();
  }

// 弹窗
  showLogoutDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('退出登录'),
        content: const Text('确定退出登录吗？'),
        actions: [
          TextButton(
            onPressed: () {
              // 退出登录
              // print('退出登录');

              tokenManager.removeToken();
              userInfo = {};
              setState(() {});
              widget.changeIndex(0);
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text(
          '我的',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
            padding: const EdgeInsets.all(10),
            child: GestureDetector(
              onTap: () {
                // Navigator.pushNamed(context, '/profile');
              },
              child: Row(
                children: getTitleChild(),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: getChildren(),
            ),
          ),
          TextButton(
            onPressed: () {
              // 退出登录
              showLogoutDialog();
            },
            style: TextButton.styleFrom(
              backgroundColor: const Color.fromRGBO(11, 87, 208, 1),
              foregroundColor: Colors.white,
            ),
            child: const Text('退出登录'),
          )
        ],
      ),
    );
  }
}
